<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-5-30
 * Time: 14:57
 */

namespace zhtfrontend\controllers;

use common\components\helpers\Util;
use EasyWeChat\Server\BadRequestException;
use zhtfrontend\components\bases\BaseController;
use common\components\helpers\Fun;
use zhtfrontend\models\datas\Admin;
use zhtfrontend\models\datas\Arrangement;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassroomAttr;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\Comment;
use zhtfrontend\models\datas\CommentRelation;
use zhtfrontend\models\datas\GoodsAttr;
use zhtfrontend\models\datas\GoodsClassTime;
use zhtfrontend\models\datas\LessonStudent;
use common\models\datas\Student;
use zhtfrontend\models\forms\ClassmanageSearchForm;
use yii\helpers\ArrayHelper;
use yii\rest\ViewAction;
use yii\web\NotFoundHttpException;
use yii\data\Pagination;

class GrowthlogController extends BaseController
{

    public function actionIndex()
    {
        $search_data = \Yii::$app->request->get();

        $class_manage = ClassManage::find()->indexBy('class_id')->where(['status'=>[1,2]])->orderBy('status DESC,class_id DESC ');
        if (!empty($search_data['course'])) {
            $arrangement_id1=Arrangement::findBySql("select a.id from {{%arrangement}} a left Join {{%course}} b on a.course_id=b.id where b.name like '%{$search_data['course']}%'" )->column();
            $goods_attr_id1=GoodsAttr::findBySql("select goods_id from {{%goods_attr}} where obj_type='course' and value like '%{$search_data['course']}%'")->column();
            $class_manage->andWhere(['or',['and',['in','associate_id',$arrangement_id1],'is_old'=>1],['and',['in','associate_id',$goods_attr_id1],'is_old'=>0]]);
        }
        if (!empty($search_data['teacher'])) {
            $arrangement_id2=Arrangement::findBySql("select a.id from {{%arrangement}} a left Join {{%teacher}} b on a.teacher_id=b.id where b.name like '%{$search_data['teacher']}%'" )->column();
            $goods_attr_id2=GoodsAttr::findBySql("select goods_id from {{%goods_attr}} where obj_type='teacher' and value like '%{$search_data['teacher']}%'")->column();
            $class_manage->andWhere(['or',['and',['in','associate_id',$arrangement_id2],'is_old'=>1],['and',['in','associate_id',$goods_attr_id2],'is_old'=>0]]);
        }
        if (!empty($search_data['classroom'])) {
            $arrangement_id3=Arrangement::findBySql("select a.id from {{%arrangement}} a left Join {{%classroom}} b on a.classroom_id=b.id where b.name like '%{$search_data['classroom']}%'" )->column();
            $goods_attr_id3=GoodsAttr::findBySql("select goods_id from {{%goods_attr}} where obj_type='classroom_name' and value like '%{$search_data['classroom']}%'")->column();
            $class_manage->andWhere(['or',['and',['in','associate_id',$arrangement_id3],'is_old'=>1],['and',['in','associate_id',$goods_attr_id3],'is_old'=>0]]);
        }

        //老师看属于自己的班级
        $role = isset(\Yii::$app->user->identity)?\Yii::$app->user->identity->role:'';
        if($role == 'teache_teacher'){
            $arrangement_id4=Arrangement::find()->select('id')->where(['teacher_id'=>\Yii::$app->user->identity->teacher_id])->column();
            $goods_attr_id4=GoodsAttr::find()->select('goods_id')->where(['attribute_id'=>\Yii::$app->user->identity->teacher_id])->column();
            $class_manage->andWhere(['or',['and',['in','associate_id',$arrangement_id4],'is_old'=>1],['and',['in','associate_id',$goods_attr_id4],'is_old'=>0]]);
        }

        $pages = new Pagination(['totalCount' =>$class_manage->count(), 'pageSize' =>10,'params'=>array_merge($_GET,$search_data)]);
        $class_manage = $class_manage->offset($pages->offset)->limit($pages->limit)->all();
        $class_count = [];
        if ($class_manage != null) {
            foreach ($class_manage as $k => $v) {
                $count = ClassStudent::find()->where(['class_manage_id' => $k])->count();
                $class_count[$k]['id'] = $k;
                $class_count[$k]['is_old'] = $v->is_old;
                $class_count[$k]['start_time'] = $v->start_time;
                $class_count[$k]['end_time'] = $v->end_time;
                $class_count[$k]['COUNT(id)'] = $count;
                $class_count[$k]['avatar'] = 'images/images/noperson.png';
                if($v->is_old == 0){
                    $good_attr=[];
                    $goods_attr=GoodsAttr::find()->where(['goods_id'=>$v->associate_id])->asArray()->all(Fun::getSiteDb());
                    if($goods_attr!=null){
                        $good_attr=ArrayHelper::map($goods_attr,'obj_type','value');
                    }
                    $str = '';
                    $class_time = GoodsClassTime::find()->where(['goods_id'=>$v->associate_id])->all();
                    if($class_time){
                        foreach($class_time as $c){
                            $str .= Util::getWeek($c->class_day).$c->start_time.'-'.$c->end_time.' ';
                        }
                    }
                    $class_count[$k]['course_name'] = isset($good_attr['course'])?$good_attr['course']:'';
                    $class_count[$k]['teacher_name'] = isset($good_attr['teacher'])?$good_attr['teacher']:'';
                    $class_count[$k]['classroom_name'] = isset($good_attr['classroom_name'])?$good_attr['classroom_name']:'';
                    $class_count[$k]['class_time'] = $str;
                    $class_count[$k]['max_number'] =  isset($good_attr['max_number'])?$good_attr['max_number']:'';
                    $class_count[$k]['opening_number'] = isset($good_attr['opening_number'])?$good_attr['opening_number']:'';
                }else{
                    $class_count[$k]['course_name'] = isset($v->arrangeMent->course)?$v->arrangeMent->course->name:'';
                    $class_count[$k]['teacher_name'] = isset($v->arrangeMent->teacher)?$v->arrangeMent->teacher->name:'';
                    $class_count[$k]['classroom_name'] = isset($v->arrangeMent->classroom)?$v->arrangeMent->classroom->name:'';
                    $str = '';
                    if(isset($v->arrangeMent) && $v->arrangeMent->classroom_attr_id){
                        $classattr_id = explode(',',$v->arrangeMent->classroom_attr_id);
                        $c_list = ClassroomAttr::find()->where(['id'=>$classattr_id])->all();
                        if($c_list){
                            foreach($c_list as $v){
                                $str .= Fun::getClassTime($v->start_time,$v->end_time,$v->classday);
                            }
                        }
                    }
                    $class_count[$k]['class_time'] = $str;
                    $class_count[$k]['max_number'] =isset($v->arrangeMent)?$v->arrangeMent->max_number:'';
                    $class_count[$k]['opening_number'] = isset($v->arrangeMent)?$v->arrangeMent->opening_number:'';
                }
            }
        }
        return $this->render('index', ['data' => $class_count,'pages'=>$pages]);
    }

    public function actionStudent(){
//        $this->layout='@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $student_id = ClassStudent::find()->select('student_id')->where(['class_manage_id' =>\Yii::$app->request->get('id')])->asArray()->column();
        $student = Student::find()->where(['id' => $student_id])->all();
        return $this->render('student', ['student' => $student, 'class_id' => \Yii::$app->request->get('id')]);

    }

    public function actionGrowth(){
//        $this->layout='@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null || \Yii::$app->request->get('class_id') == null) {
            throw new BadRequestException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $class_id= \Yii::$app->request->get('class_id');
        $id= \Yii::$app->request->get('id');
        $class_lesson=ClassLesson::find()->select('lesson_id')->where(['class_id'=>$class_id])->column(Fun::getSiteDb());
        $lesson_student=LessonStudent::find()->where(['in','lesson_id',$class_lesson])->andWhere(['student_id'=>$id])->all(Fun::getSiteDb());
        return $this->render('growth', ['lesson_student' => $lesson_student,'student_id'=>$id]);

    }


    public function actionAdd(){
//        $this->layout='@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('lesson_id') == null || \Yii::$app->request->get('student_id') == null) {
            throw new BadRequestException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $lesson_id=\Yii::$app->request->get('lesson_id');
        $student_id=\Yii::$app->request->get('student_id');
        $class_lesson=ClassLesson::findOne(['lesson_id'=>$lesson_id]);
        if($class_lesson==null){
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model=LessonStudent::find()->where(['lesson_id'=>$lesson_id,'student_id'=>$student_id])->one(Fun::getSiteDb());



        //学生家长对老师、班主任的评价
        $comment = Comment::find()->where(['lesson_student_id'=>$model->id,'valuator_type'=>2,'accepter_type'=>1])->all();
        $teache_teacher = [];
        $class_teacher = [];
        $manager = [];
        foreach ($comment as $k=>$v){
            //查询评价分数
            $score = [];
            foreach ($v->commentRelations as $ck=>$cv){
                $score[$ck] = [
                    'title' => $cv->commentInfo->title,
                    'value' => $cv->for_value,
                ];
            }

            $admin = Admin::findOne(['id'=>$v->accepter_id]);
            if($admin->role == 'teache_teacher'){
                $teache_teacher[$k] = [
                    'title' => $v->title,
                    'description' => $v->description,
                    'score' => $score,
                ];
            }elseif($admin->role == 'class_teacher'){
                $class_teacher[$k] = [
                    'title' => $v->title,
                    'description' => $v->description,
                    'score' => $score,
                ];
            }elseif($admin->role == 'manager'){
                $manager[$k] = [
                    'title' => $v->title,
                    'description' => $v->description,
                    'score' => $score,
                ];
            }
        }

        //班主任可查看家长对老师的评价
        $comment_data = [];
        if(\Yii::$app->user->identity->role == 'class_teacher'){
            $comment_data = [
                'teache_teacher' => $teache_teacher,
            ];
        }elseif (\Yii::$app->user->identity->role == 'manager'){
            $comment_data = [
                'teache_teacher' => $teache_teacher,
                'class_teacher' => $class_teacher,
            ];
        }elseif (\Yii::$app->user->identity->role == 'admin' || \Yii::$app->user->identity->role == 'administrator'){
            $comment_data = [
                'teache_teacher' => $teache_teacher,
                'class_teacher' => $class_teacher,
                'manager' => $manager,
            ];
        }




        $model->addValidateandbehavior();
        if($model==null){
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        if($model->load(\Yii::$app->request->post())&&$model->validate()){

            $postdata = \Yii::$app->request->post();
//            var_dump($postdata);die;
            if(!empty($postdata['LessonStudent']['imageList'])){
                $imagelist = $postdata['LessonStudent']['imageList'];
                $imagelist_arr = [];
                if(!empty($imagelist)){
                    $imagelist_arr = explode('#|#',$imagelist);
                }
                if(!empty($postdata['LessonStudent']['defaulturl']) && in_array($postdata['LessonStudent']['defaulturl'],$imagelist_arr)){
                    $model->picture = $postdata['LessonStudent']['defaulturl'];
                }else{
                    if(count($imagelist_arr)>0){
                        $model->picture = $imagelist_arr[0];//上传的列表第一个作为展示的默认图
                    }else{
                        $model->picture = '';
                    }
                }
            }else{
                $model->picture = '';
            }

            $model->check_time=$class_lesson->class_date;
            $model->status=$class_lesson->status;
            if($model->save(false)){
                return $this->redirect(Fun::url(['growthlog/growth','id'=>$student_id,'class_id'=>$class_lesson->class_id]));
            }
        }
       // print_r($model);exit;
        return $this->render('add', ['model' =>$model,'comment_data'=>$comment_data]);
    }


}